﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DbFrame.ExpressionTree.Class
{
    using System.Linq.Expressions;
    using DbFrame.Class;
    using System.Collections;

    public class SelectParser
    {


        public SelectParser(LambdaExpression _LambdaExpression, StringBuilder Code, Dictionary<string, string> Alias, Dictionary<string, object> Param)
        {
            var body = (_LambdaExpression.Body as NewExpression);
            if (body == null) throw new Exception("语法错误 这里请使用 new {  } 匿名实例化语法！");
            var values = body.Arguments;
            var member = body.Members;
            var column = new List<string>();
            foreach (var item in _LambdaExpression.Parameters)
            {
                var _Model = (BaseEntity)Activator.CreateInstance(item.Type);
                Alias.Add(item.Name, _Model.GetTabelName());
            }
            Code.Append("SELECT ");
            var list_member = member.ToList();
            foreach (var item in values)
            {
                if (item is MemberExpression)
                {
                    var it = item as MemberExpression;
                    //检查是否有别名
                    var DisplayName = list_member[values.IndexOf(item)].Name;
                    if (DisplayName == it.Member.Name)
                        column.Add((it.Expression as ParameterExpression).Name + "." + it.Member.Name);
                    else
                        column.Add((it.Expression as ParameterExpression).Name + "." + it.Member.Name + " AS " + DisplayName);
                }
                else if (item is ConstantExpression)
                {
                    var it = item as ConstantExpression;
                    var val = it.Value;
                    //检查是否有别名 ''
                    var DisplayName = list_member[values.IndexOf(item)].Name;
                    if (!string.IsNullOrEmpty(DisplayName))
                        column.Add(" '" + val + "' " + " AS " + DisplayName);
                }
            }
            Code.Append(string.Join(",", column));
            var ByName = _LambdaExpression.Parameters[0].Name;
            var TabName = Alias[ByName] + " AS " + ByName;
            Code.Append(" FROM " + TabName);
        }








    }
}
